package edu.ptu.shortlink.project.service.impl;

import edu.ptu.shortlink.project.service.IUrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.project.service.impl
 * @Author: HYJ
 * @CreateTime: 2025-05-01  15:01
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class UrlServiceImpl implements IUrlTitleService {

    @SneakyThrows
    @Override
    public String getUrlTitle(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");

        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            Document document = Jsoup.connect(url).get();
            return document.title();
        }
        return "Error while fetching the URL";
    }
}
